﻿#coding=utf-8
from django.contrib import auth
from django.http import HttpResponse
from django.template import RequestContext
from django.utils import simplejson
from django.views.decorators.csrf import csrf_protect
from django.core.exceptions import ObjectDoesNotExist
from django.contrib.auth.models import User 
from user_handle.models import UserProfile

def register(request):
    if request.method == 'GET':
        username = request.GET.get('username', '')
        password = request.GET.get('password', '')
        location = request.GET.get('location', '')
        name = request.GET.get('name', '')
        try:
            user = User.objects.get(username = username)
            return HttpResponse(simplejson.dumps({'msg':'用户名已被使用'}))
        except:
            user = User.objects.create_user(username=username, email=username, password=password)
            try:
                profile = user.get_profile()
            except ObjectDoesNotExist:
                # create profile
                profile = UserProfile(user=user,location=location,name=name)
                profile.save()
            if user is not None:
                return HttpResponse(simplejson.dumps({'msg':'OK'}))
            else:  
                return HttpResponse(simplejson.dumps({'msg':'好像有些技术问题（创建失败）'}))            
    else:
        return HttpResponse(simplejson.dumps({'msg':'好像有些技术问题（非GET）'}))

@csrf_protect        
def login(request):
    if request.method == 'POST':
        username = request.POST.get('username', '')
        password = request.POST.get('password', '')
        user = auth.authenticate(username=username, password=password)
        if user is not None and user.is_active:
            print "password:" + password + "\n"
            auth.login(request,user)
            return HttpResponse(simplejson.dumps({'msg':'OK'}))
        else:
            return HttpResponse(simplejson.dumps({'msg':'用户名或密码好像错了哦'}))
    else:
        return HttpResponse(simplejson.dumps({'msg':'非post'}))
        
def logout(request):
    auth.logout(request)